#-*- coding:utf-8 -*-
import thread,time,sys,ctypes
try:
    from Tkinter import Frame,Spinbox,GROOVE,RIDGE,Text,Button,Label,Entry,StringVar,Tk,Checkbutton,LEFT,W,OptionMenu,DISABLED,NORMAL,LabelFrame,E,IntVar
    import tkFileDialog,tkFont
    import tkMessageBox
except:
    print "Warn:Gui will fail without tkinter lib"
class Application(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)

        self.init_var()
        toplevel=self.winfo_toplevel()
        toplevel.title(self.title)
        toplevel.resizable(False,False)
        toplevel.geometry("{0}x{1}+1300+0".format(self.small_width,self.height))
        self.grid()

        self.init_ui()
        
    def init_ui(self):
        self.main_frame=Frame(self,relief=GROOVE,bd=2)
        self.label_drv=Label(self.main_frame,text=u"选择监视驱动",width=19)
        self.label_drv.grid(column=0,row=0)
        self.menu_drv=OptionMenu(self.main_frame,self.drv_string,*self.drv_list)
        self.menu_drv.grid(column=1,row=0,columnspan=2,sticky=E)
        self.menu_drv["width"]=26
        self.label1=Label(self.main_frame,text=u"剩余空间")
        self.label1.grid(column=0,row=1)
        self.label2=Label(self.main_frame,textvariable=self.free_space,width=15,relief=GROOVE,bd=1)
        self.label2.grid(column=1,row=1)
        self.label3=Label(self.main_frame,textvariable=self.free_status,width=15,relief=GROOVE,bd=1)
        self.label3.grid(column=2,row=1,sticky=E)
        self.button1=Button(self.main_frame,text=u"开始监视",width=15,command=self.button_click)
        self.button1.grid(column=0,row=2)
        self.button_set=Button(self.main_frame,text=u"设置>>",command=self.setting,anchor=E)
        self.button_set.grid(column=2,row=2,sticky=E)
        self.main_frame.grid(column=0,row=0,ipadx=1,padx=1,ipady=2)
        
        self.set_frame=Frame(self,relief=GROOVE,bd=2,height=10)
        self.set_frame.grid(column=1,row=0,padx=1,ipady=8,pady=1)
        self.interval_label=Label(self.set_frame,text=u"刷新频率")
        self.interval_label.grid(column=0,row=0,sticky=W)
        self.interval_spin=Spinbox(self.set_frame,from_=1,to=10,wrap=True,width=7,textvariable=self.interval_value)
        self.interval_spin.grid(column=1,row=0,padx=2)
        self.alert_check=Checkbutton(self.set_frame,text=u"若某时间内空间未变化时弹出提醒",variable=self.check_value,command=self.checkbutton_check)
        self.alert_check.grid(column=0,row=1,columnspan=2)
        self.alert_count_label=Label(self.set_frame,text=u"选择时间")
        self.alert_count_label.grid(column=0,row=2,sticky=E)
        self.alert_count_spin=Spinbox(self.set_frame,from_=0,to=100,width=7,wrap=True,textvariable=self.check_pick_time)
        self.alert_count_spin.grid(column=1,row=2)
        self.alert_count_label["state"]=DISABLED
        self.alert_count_spin["state"]=DISABLED
        self.status_label=Label(self,textvariable=self.status_str,font=tkFont.Font(size=8))
        self.status_label.grid(column=0,row=1,sticky=W)
    def checkbutton_check(self):
        value=self.check_value.get()
        if value==0:
            self.alert_count_label["state"]=DISABLED
            self.alert_count_spin["state"]=DISABLED
        else:
            self.alert_count_label["state"]=NORMAL
            self.alert_count_spin["state"]=NORMAL
    def button_click(self):
        self.button1.bell()
        if self.is_pause:
            self.is_pause=False
            self.resume_watch()
            self.button1["text"]=u"暂停监视"
            self.menu_drv["state"]=DISABLED
            self.button_set["state"]=DISABLED
            if not self.setting_is_click:
                self.setting()
        else:
            self.is_pause=True
            self.pause_watch()
            self.button1["text"]=u"开始监视"
            self.menu_drv["state"]=NORMAL
            self.button_set["state"]=NORMAL
    def setting(self):
        cur_pos=self.winfo_toplevel().geometry()
        if self.setting_is_click:
            self.setting_is_click=False
            self.winfo_toplevel().geometry("{0}x{1}".format(self.large_width,self.height)+cur_pos[cur_pos.index("+"):])
            self.button_set["text"]=u"设置<<"
        else:
            self.setting_is_click=True
            self.winfo_toplevel().geometry("{0}x{1}".format(self.small_width,self.height)+cur_pos[cur_pos.index("+"):])
            self.button_set["text"]=u"设置>>"
    def format_number(self,num):
        if not num:
            return "0"
        for v in self.unit:
            if num>=v[0]:
                return "{0:.2f}{1}".format(num/v[0],v[1])
    def init_var(self):
        self.title=u"空间监视"
        self.height=110
        self.large_width=588
        self.small_width=374
        self.unit=((1024*1024*1024.,"GB"),(1024*1024.,"MB"),(1024.,"KB"),(1,"Byte"),(0,"Byte"))
        self.last_value=-1
        self.counter=0
        self.is_pause=True
        self.setting_is_click=True
        self.free_space=StringVar(self,value="0")
        self.free_status=StringVar(self,value="0")
        self.free_bytes = ctypes.c_ulonglong(0)
        self.drv_list=self.get_drv_list()
        self.drv_string=StringVar(self,value=self.drv_list[0])
        self.interval_value=IntVar(self,value=1)
        self.status_str=StringVar(self,value="")
        self.check_value=IntVar(self,value=0)
        self.check_pick_time=IntVar(self,value=1)
    def get_drv_list(self):
        lpBuffer = ctypes.create_string_buffer(78)
        ctypes.windll.kernel32.GetLogicalDriveStringsA(ctypes.sizeof(lpBuffer), lpBuffer)
        vol = lpBuffer.raw.split('\x00')
        return tuple([i for i in vol if i])

    def pause_watch(self):
        self.counter=0
        self.winfo_toplevel().title(self.title+u"--暂停中")
        self.alert()
    def resume_watch(self):
        self.last_value=-1
        self.winfo_toplevel().title(self.title+u"--监视中")
        self.menu_drv.state=DISABLED
        thread.start_new_thread(self.get_free_space,())
    def get_free_space(self):
        drv_str=self.drv_string.get()
        refresh_frq=unicode(self.interval_value.get())
        self.status_str.set(u"刷新率:"+refresh_frq)
        while(1):
            ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(drv_str), None, None, ctypes.pointer(self.free_bytes))
            status=u"减少"
            status_value=0
            if self.last_value>0:
                if self.free_bytes.value>self.last_value:
                    status=u"增加:"
                    self.label3["bg"]="#FF6666"
                    self.counter=0
                elif self.free_bytes.value==self.last_value:
                    print self.counter

                    status=u"无变化:"
                    self.label3["bg"]="#6699FF"
                    self.status_str.set(u"")
                    if self.check_value.get():
                        self.counter+=1
                        if self.check_pick_time>self.counter :
                            self.alert()
                            self.counter=0
                else:
                    status=u"减少:"
                    self.label3["bg"]="#00FF66"
                    self.counter=0
                status_value=abs(self.free_bytes.value-self.last_value)
            self.last_value=self.free_bytes.value                
            self.free_space.set(self.format_number(self.free_bytes.value))
            self.free_status.set(status+unicode(self.format_number(status_value)))
            if self.is_pause:
                break
            time.sleep(self.interval_value.get())
    def alert(self):
        #tkMessageBox.showwarning(u"硬盘已断开",u"所监视硬盘["+unicode(self.drv_string.get())+"]已经无法访问，请确认连接。本程序自动暂停监视")
        tkMessageBox.showwarning("Disk Disconnected","The Watching Disk["+unicode(self.drv_string.get())+"] is unavailable,Please!Stop Watching automately!")
    def ask(self):
        tkMessageBox.askquestion(u"注意容量变化",u"监视到已经有")
if __name__=="__main__":
    if len(sys.argv)==1:
        tk=Tk()
        app=Application(tk)
        app.mainloop()
